/**

 @Name: 用户模块

 */
 
layui.define(['laypage', 'element', 'flow', 'table', 'laydate' ,'upload'], function(exports){

  var $ = layui.jquery;
  var layer = layui.layer;
  var util = layui.util;
  var laytpl = layui.laytpl;
  var form = layui.form;
  var laypage = layui.laypage;
  var fly = layui.fly;
  var flow = layui.flow;
  var element = layui.element;
  var upload = layui.upload;
  var table = layui.table;
  var laydate = layui.laydate;

  
  rechargeLog();



  //余额充值
  $('#input_val_btn').on('click', function(event) {
  	 $(this).hide();
  	 $('#input_val').show();

  });

  //查看协议
  $('#lazada-bill-agreement').on('click', function(){
    layer.open({
      type: 1
      ,title: '余额充值协议'
      ,area: ['310px', '450px']
      ,content: ['<div class="layui-text" style="padding: 5px 15px; font-size: 12px;">'
        ,'<ul>'
          ,'<li>1. 余额充值后不予退款。</li>'
          ,'<li>2. 仅支持本地台消费。</li>'
        ,'</ul>'
      ,'</div>'].join('')
      ,shadeClose: true
    });
  });

  $('.layui-recharge-item').on('click', 'button', function(event) {
  	 var money = $(this).data('money');
     $('#input_val').hide();
     $('#input_val_btn').show();
  	 $('#input_val').val(money);
  	 $('#LAY_price').text('￥'+money);
  	 $(this).addClass('layui-this');
  	 $(this).siblings('button').removeClass('layui-this');
  	
  });


  $('#input_val').on('keyup', function(event) {
  	 $('#LAY_price').text('￥'+$(this).val());
  });


  element.on('tab(recharge)', function(){
    var othis = $(this), layid = othis.attr('lay-id');
    if(layid){
      window.location.href = layid;
    }
  });

  element.on('tab(pack)', function(){
    var othis = $(this), layid = othis.attr('lay-id');
    if(layid){
      window.location.href = layid;
    }
  });

  //显示当前tab
  if(location.hash){
    element.tabChange('user', location.hash.replace(/^#/, ''));
  }

  element.on('tab(user)', function(){
    var othis = $(this), layid = othis.attr('lay-id');
    if(layid){
      location.hash = layid;
    }
  });

    //上传图片
    if($('.upload-img')[0]){
      layui.use('upload', function(upload){
        var avatarAdd = $('.avatar-add');

        upload.render({
          elem: '.upload-img'
          ,url: 'upload'
          ,size: 50
          ,before: function(){
            avatarAdd.find('.loading').show();
          }
          ,done: function(res){
            if(res.status == 1){
              $.post('set', {
                head_pic: res.url
              }, function(res){
                location.reload();
              });
            } else {
              layer.msg(res.msg, {icon: 5});
            }
            avatarAdd.find('.loading').hide();
          }
          ,error: function(){
            avatarAdd.find('.loading').hide();
          }
        });
      });
    }


  //充值记录表单
  function rechargeLog(){
     table.render({
      elem: '#LAZADA_RechargeList'
      ,url: 'rechargeLog' //数据接口
      ,method:'post'
      ,where: {sTime: 'sasasas', eTime: 123} //如果无需传递额外参数，可不加该参数
      ,page: true //开启分页
      ,cols: [[ //表头
        {field: 'ctime', title: '日期', width:200,sort: true,align:'center',templet: '#ctimeTpl'}
        ,{field: 'account', title: '金额', width:150,sort: true ,align:'center'}
        ,{field: 'order_sn', title: '充值单号', width:200 ,align:'center'}
        ,{field: 'pay_name', title: '支付方式', width:150 ,align:'center'}
        ,{field: 'pay_status', title: '状态' ,align:'center' ,templet:'#statusTpl'} 
      ]]
      ,text:{
          none:'没有任何充值（立即充值：<a href="recharge" class="fly-link">余额充值</a>）'
      }
    });
  }

 

  //资金明细表单
  table.render({
      elem: '#LAZADA_AccountList'
      ,url: 'AccountLog' //数据接口
      ,method:'post'

      ,page: true //开启分页
      ,cols: [[ //表头
        {field: 'change_time', title: '日期', width:200,sort: true,align:'center',templet: '#changeTpl'}
        ,{field: 'user_money', title: '余额', width:150,sort: true,align:'center'}
        ,{field: 'pay_points', title: '积分', width:150,sort: true,align:'center'}
        ,{field: 'order_sn', title: '订单号', width:200,sort: true,align:'center',}
        ,{field: 'desc', title: '备注',align:'center',} 
      ]]
      ,text:{
          none:'没有任何记录'
      }
    });

  //打包记录表
  // table.render({
  //     elem: '#LAZADA_PackList'
  //     ,url: 'packlist' //数据接口
  //     ,method:'post'
  //     ,skin:'line'
  //     ,page: true //开启分页
  //     ,cols: [[ //表头
  //       {field: 'crate_time', title: '添加时间', width:180,sort: true,align:'center',templet: '#timeTpl'}
  //       ,{field: 'pack_number', title: '面单编号', width:200,sort: true,align:'center'}
  //       ,{field: 'pack_file', title: '文件', width:80,sort: true,align:'center',templet:'#fileTpl'}
  //       ,{field: 'pack_status_name', title: '订单状态', width:150,sort: true,align:'center'}
  //       ,{field: 'pay_status_name', title: '支付状态', width:150,sort: true,align:'center'}
  //       ,{field: 'pack_id', title: '操作',align:'center',toolbar:'#parkBar'} 
  //     ]]
  //     ,id: 'pack_number'
  //     ,text:{
  //         none:'没有任何面单记录（立即：<a href="packadd" class="fly-link">添加打包</a>）'
  //     }
  //   });

  //方法级渲染
  table.render({
    elem: '#LAZADA_PackList'
    ,url: 'packlist'
    ,toolbar: '#toolbarDemo'
    ,method:'post'
    ,cols: [[
         {type: 'checkbox', fixed: 'left'}
        ,{field: 'pack_id', title: '编号', width:150,sort: true,fixed: 'left',align:'center'}
        ,{field: 'crate_time', title: '添加时间', width:180,sort: true,align:'center',templet: '#timeTpl'}
        ,{field: 'pack_number', title: '面单编号', width:200,sort: true,align:'center',event: 'setPack',templet:'#packNumberTpl'}
        ,{field: 'pack_file', title: '文件', width:80,align:'center',templet:'#fileTpl'}
        ,{field: 'pack_status_name', title: '订单状态', width:150,sort: true,align:'center'}
        ,{field: 'pay_status_name', title: '支付状态', width:150,sort: true,align:'center'}
        ,{field: 'platform_code', title: '平台', width:150,sort: true,align:'center'}
        ,{field: 'pack_id', title: '操作',width:150,align:'center',toolbar:'#parkBar',fixed: 'right'} 
    ]]
    ,where: {
          pack_number: $('#pack_number').val(),
          pack_status: $('#pack_status option:selected').val(),
          platform_code:$('#platform_code option:selected').val(),
      }
    ,id: 'testReload'
    ,page: true
  });
  
  var $ = layui.$, active = {
    getCheckData: function(){ //获取选中数据
      var checkStatus = table.checkStatus('testReload')
      ,data = checkStatus.data;
      if (data=='') {
        layer.alert('请至少选择一条记录');return;
      }
      // var postData = JSON.stringify(data);
      layer.confirm('您确认对勾选数据进行支付并且提交打包信息?', function(index){
          $.post('batchPay',{data:data},function(data){
            if(data.status==1){
              layer.msg(data.msg);
              setTimeout(function(){
                window.location.reload();
              },2000)
            }else{
              layer.msg(data.msg);
              
            }
          },'json');
          layer.close(index);
      });
      
      
    }
    ,getCheckLength: function(){ //获取选中数目
      var checkStatus = table.checkStatus('testReload')
      ,data = checkStatus.data;
      layer.msg('选中了：'+ data.length + ' 个');
    }
    ,isAll: function(){ //验证是否全选
      var checkStatus = table.checkStatus('testReload');
      layer.msg(checkStatus.isAll ? '全选': '未全选')
    }
    ,reload: function(){
      var demoReload = $('#pack_number');
     
      //执行重载
      table.reload('testReload', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        ,where: {
          pack_number: demoReload.val(),
          pack_status: $('#pack_status option:selected').val(),
          platform_code: $('#platform_code option:selected').val(),

        }
      });
    }
  };


  
  $('#LAY_ucm .layui-btn').on('click', function(){
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
  });


   //商品记录表
  table.render({
      elem: '#LAZADA_GoodsList'
      ,url: 'goodsList'//数据接口
      ,method:'post'
      ,height: 400 //固定值
      ,page: true //开启分页
      ,cols: [[ //表头
         {field: 'create_time', title: '时间', width:200,sort: true,align:'center',templet: '#timeTpl'}
        ,{field: 'goods_name', title: '商品标题', width:200,sort: true,align:'center'}
        ,{field: 'goods_num', title: '数量', width:80,sort: true,align:'center'}
        ,{field: 'goods_origin', title: '主图', width:100,align:'center',templet:'#originTpl'}
        ,{field: 'express_code', title: '快递编码',align:'center',width:150} 
        ,{field: 'express_number', title: '快递单号',align:'center'} 
      ]]
      ,text:{
          none:'没有任何面单记录（立即：<a href="{:url("user/packlist")}" class="fly-link">添加打包</a>）'
      }
    });


    


  // 监听工具条
  var checkedArr=[];
  table.on('tool(packList)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
    var data = obj.data; //获得当前行数据
    var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
    var html = '<div class="layui-card">'+
                  '<div class="layui-card-body">'+data.pack_note+'</div>'+
                '</div>';
	  var pack_id = data.pack_id;




    if (layEvent=='detail') {
      window.location.href = 'packinfo/id/'+data.pack_id;
    }else if(layEvent=='cancel'){
      layer.confirm('面单取消后不可恢复,您确取消?', function(index){
          $.post('packCancel',{pack_id:pack_id},function(data){
          if(data.status==1){
            layer.msg(data.msg);
            setTimeout(function(){
              window.location.reload();
            },2000)
          }else{
            layer.msg(data.msg);
            
          }
        },'json');
        });
    }else if(layEvent=='checkedpay'){
         checkedArr[obj.data.id] = obj.data.LAY_TABLE_INDEX;
    }else if(layEvent=='setPack'){
      layer.prompt({
        formType: 2
        ,title: '修改面单编号'
        ,value: data.pack_number
      }, function(value, index){
        layer.close(index);
        $.post('/Index/Index/changeTableVal', {table: 'pack',id_name:'pack_id',id_value:pack_id,field:'pack_number',value:value}, function(data, textStatus, xhr) {
              layer.msg('更新成功');
        },'json');
        //这里一般是发送修改的Ajax请求
        
        //同步更新表格和缓存对应的值
        obj.update({
          pack_number: value
        });
      });
    }else if(layEvent=='goods'){
      window.location.href = 'goodsList/id/'+data.pack_id;
    }else if(layEvent=='pay'){
		layer.confirm('您确认完成支付并且提交打包信息?', function(index){
		  $.post('applyPay',{pack_id:pack_id},function(data){
			  if(data.status==1){
				  layer.msg(data.msg);
				  setTimeout(function(){
					  window.location.reload();
				  },2000)
			  }else{
				  layer.msg(data.msg);
				  
			  }
		  },'json');
		  layer.close(index);
		});     
    }

  });

   //开始日期
    var insStart = laydate.render({
      elem: '#rechargeLog-laydate-start'
      ,min: 0
      ,done: function(value, date){
        //更新结束日期的最小日期
        insEnd.config.min = lay.extend({}, date, {
          month: date.month - 1
        });
        
        //自动弹出结束日期的选择器
       insEnd.config.elem[0].focus();
      }
    });
    
    //结束日期
    var insEnd = laydate.render({
      elem: '#rechargeLog-laydate-end'
      ,min: 0
      ,done: function(value, date){
        //更新开始日期的最大日期
        insStart.config.max = lay.extend({}, date, {
          month: date.month - 1
        });
      }
    });

    //查看物流公司编码
    $("#L_company_code").on('click', function(event) {
      $.get('get_company_code', function(data) {
         var index = layer.open({
            title:'物流公司编码'
            ,content: data
          });
      });
    });

    //添加打包表单验证
    $('#L_add_goods_row').on('click', function(event) {
    var html = $(".goods-info-item").prop("outerHTML");
    var removeHtml = '<div class="layui-form-mid layui-word-aux">'+
                         '<i class="layui-icon layui-icon-close remove-goods-row" style="color:#FF5722;font-size: 24px;"></i>'+   
                     '</div>';
    $(this).parent().before(html);

    $('.goods-info-item').last().append(removeHtml)
    form.render('select');
    });

    //移除商品行
    $('#L_goods_pack_info').on('click', '.remove-goods-row', function(event) {

      $(this).parent().parent().slideUp(200, function() {//slide up
        $(this).remove();
      });
       
    });

    


    

    
    
     

  exports('user', {});
  
});